﻿using BookSleeve;
using Castle.Core.Configuration;
using Inovout.Application;
using Inovout.YunYao.Live.Web.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Inovout.YunYao.Live.Web.Controllers
{
    public class ChartController : Controller
    {
        public ActionResult Index(long node)
        {
            ViewBag.MaxSecond = 100;
            ViewBag.IntervalSecond = 5;
            ViewBag.Interval = 5;
            ViewBag.Node = node;
            List<MonitorData> list = GetFromRedis(node);
            if (list.Count == 0)
            {
                ViewBag.StartTime = Decimal.ToInt64(Decimal.Divide(DateTime.UtcNow.Ticks - 621355968000000000, 10000));
            }
            else
            {
                ViewBag.StartTime = list[0].timestamp;

            }
            ViewData.Model = Newtonsoft.Json.JsonConvert.SerializeObject(list,
                new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
            return View();
        }

        private List<MonitorData> GetFromRedis(long node)
        {
            List<MonitorData> list = new List<MonitorData>();
            IApplication application = ComponentRegistry.Resolve<IApplication>();
            IConfiguration redisConfiguration = application.Configuration.Children["redis"];
            using (var redisConnection
                = new RedisConnection(redisConfiguration.Attributes["ip"], int.Parse(redisConfiguration.Attributes["port"].Trim())))
            {
                redisConnection.Open();
                int dbid = int.Parse(redisConfiguration.Attributes["dbid"].Trim());
                Task<KeyValuePair<string, double>[]> task = redisConnection.SortedSets.RangeString(dbid,
                    "rt_" + node.ToString(), 0, 20, true);
                foreach (var kv in task.Result)
                {
                    MonitorData data = new MonitorData();
                    data.timestamp = (long)kv.Value;
                    foreach (var item in kv.Key.Split('&'))
                    {
                        string[] kvItem = item.Split('=');
                        switch (kvItem[0])
                        {
                            case "v":
                                data.value = int.Parse(kvItem[1]);
                                break;
                        }
                    }
                    list.Add(data);
                }
            }
            return list;
        }

        private List<MonitorData> GetFromHBase(long node)
        {
            List<MonitorData> list = new List<MonitorData>();

            return list;
        }
    }
}
